package com.hua.hiring.talent.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hua.hiring.common.Constant;
import com.hua.hiring.common.util.AESUtil;
import com.hua.hiring.talent.dao.TalentDao;
import com.hua.hiring.talent.entity.TalentEntity;

public class TalentServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	private TalentDao talentDao = new TalentDao();
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String commond = request.getParameter("commond");
		if(commond != null) {
			if("register".equals(commond)){
				register(request, response);
			}else if("validateCode".equals(commond)){
				validateCode(request, response);
			}else if("login".equals(commond)){
				login(request, response);
			}else if("logout".equals(commond)){
				logout(request, response);
			}else if("get".equals(commond)){
				get(request, response);
			}else if("main".equals(commond)){
				main(request, response);
			}else if("changePassword".equals(commond)) {
				changePassword(request,response);
			}else{
				throw new IllegalStateException("请求非法");
			}
		}
	}
	/**
	 * 求职者注册
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1
			String code = request.getParameter("code");
			String password = request.getParameter("password");
			String name = request.getParameter("name");
			String phone = request.getParameter("phone");
			String email = request.getParameter("email");
			int age = Integer.parseInt(request.getParameter("age"));
			int gender = Integer.parseInt(request.getParameter("gender"));
			StringBuilder sb = new StringBuilder();
			//防止SringBuilder的toString乱码
			//String string = new String(sb.toString().getBytes(),"UTF-8");
			String[] hobbies = request.getParameterValues("hobby");
			for(int x = 0; x < hobbies.length ; x ++) {
				if(x == hobbies.length-1) {
					sb.append(hobbies[x]);
				}else {
					sb.append(hobbies[x] + "|");
				}
			}
			//2
			TalentEntity talentEntity = new TalentEntity();
			talentEntity.setCode(code);
			//加密
			byte[] passwo = AESUtil.encrypt(password,Constant.AES_KEY);
			String pass = AESUtil.parseByte2HexStr(passwo);
			
			talentEntity.setPassword(pass);
			talentEntity.setName(name);
			talentEntity.setPhone(phone);
			talentEntity.setEmail(email);
			talentEntity.setAge(age);
			talentEntity.setGender(gender);
			talentEntity.setHobby(sb.toString());
			
			talentDao.register(talentEntity);
		
		//3
		request.getRequestDispatcher("view/talent/talent-login.jsp").forward(request, response);
	}
	/**
	 * 运用AJAX检测用户帐号是否已被占用
	 *
	 * @param: @param request
	 * @param: @param response
	 * @param: @throws ServletException
	 * @param: @throws IOException
	 * @return: void
	 * @author: 刘天印
	 * @date: 2018年12月12日 下午6:32:43
	 */
	private void validateCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1
		String code = request.getParameter("code");
		//2
		TalentEntity talent = talentDao.validate(code);
		//3 IO流
		PrintWriter printWriter = response.getWriter();
		try {
			if(talent == null) {
				printWriter.print(0);
			}else {
				printWriter.print(1);
			}
		}finally {
			printWriter.close();
		}
	}
	/**
	* @Description: 修改密码
	*
	* @param request
	* @param response
	* @throws ServletException
	* @throws IOException
	* @throws：异常描述
	*
	* @author: 刘天印
	* @date: 2018年12月19日 下午8:35:32 
	*
	 */
	private void changePassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		int talentId = Integer.parseInt(request.getParameter("id"));
		String passwordStr = request.getParameter("pass"); 
		//加密
		byte[] passwo = AESUtil.encrypt(passwordStr,Constant.AES_KEY);
		String passw = AESUtil.parseByte2HexStr(passwo);
		
		int row = talentDao.changePassword(talentId,passw);
		
		PrintWriter printWriter = response.getWriter();
		try {
			if (row == 1) {
					printWriter.print(1);
				} else {
					printWriter.print(0);
				}
		} finally {
			printWriter.close();
		}
		
	}
	/**
	 * 求职者登录
	 */
	private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.1
		String code = request.getParameter("code");
		String passwordStr = request.getParameter("password");
		String verifyCode = request .getParameter("verifyCode");
		//获取kaptcha生成存放在session中的验证码
        String kaptchaValue = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if(verifyCode == null || verifyCode == "") {
			request.setAttribute("errorInfo", "请输入验证码");
			request.getRequestDispatcher("/view/talent/talent-login.jsp").forward(request, response);
		}
		if(!verifyCode.equals(kaptchaValue)) {
			request.setAttribute("errorInfo", "验证码错误，请重新输入验证码");
			request.getRequestDispatcher("/view/talent/talent-login.jsp").forward(request, response);
		}
		//1.3得到相对应的加密密码 
		byte[] passwo = (AESUtil.encrypt(passwordStr,Constant.AES_KEY));
		String password = AESUtil.parseByte2HexStr(passwo);
		//2
		TalentEntity talent = talentDao.login(code,password);
		//3
		if(talent == null) {
			request.setAttribute("code", code);
			request.setAttribute("errorInfo", "用户名或密码错误");
			request.getRequestDispatcher("/view/talent/talent-login.jsp").forward(request, response);
		}else {
			//一个session会话 全局都可以用
			request.getSession().setAttribute("talent", talent);
			//另一个session会话 用于单态登录
			request.getSession().setAttribute("talentCode", code);
			//转发  优点： 可以携带参数   缺点：地址栏会显示Servlet的请求地址，用户可以重复提交
			//request.getRequestDispatcher("/view/talent/main.jsp").forward(request, response);
			//重定向  优点： 地址栏会不显示Servlet的请求地址，用户不可以重复提交   缺点：不可以携带参数
			response.sendRedirect("TalentServlet?commond=main");
			}
	}
	/**
	 * 求职者注销
	 */
	private void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getSession().invalidate();
		request.getRequestDispatcher("view/talent/talent-login.jsp").forward(request, response);
	}
	/**
	 * 求职者信息
	 */
	private void get(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		TalentEntity talent = talentDao.get(id);
		//解密
		byte[] pass = AESUtil.parseHexStr2Byte(talent.getPassword());
		byte[] password = AESUtil.decrypt(pass, Constant.AES_KEY);
		talent.setPassword(new String(password));
		
		request.setAttribute("talent", talent);
		request.getRequestDispatcher("view/talent/talent-info.jsp").forward(request, response);
	}
	/**
	 * 求职者主页
	 */
	private void main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String  rowStr = request.getParameter("row");
		
		if(rowStr != null) {
			int row = Integer.parseInt(rowStr);
			// 3
			if(row == 1) {
				request.setAttribute("success", "操作成功~");
			}else {
				request.setAttribute("error", "操作失败~");
			}
		}
		
		request.getRequestDispatcher("ApplicationServlet?commond=listByTelantPage").forward(request, response);
	}
	
}
